﻿// xmGJ+CFOgZtjSJhZWOb0QnxTa3KBu3LFB1I8Fd+pQPU=
﻿/// <reference path="/js/ocho.js"/>
(function () {
	"use strict";
	var resultsListView;
	var selected;

	WinJS.UI.Pages.define("/pages/results/results.html", {
		ready: function (element, options) {
			document.querySelector(".pagetitle").innerText = "Re: " + options.terms;
			var resultsList = new WinJS.Binding.List();
			WinJS.xhr({
				url: "https://api.datamarket.azure.com/Bing/Search/v1/Web?$format=json&Query=%27" + encodeURIComponent(options.terms) + "%27",
			}).then(
				function (e) {
					var results = JSON.parse(e.response).d.results.map(function(r) {
						r.documentPromise = WinJS.xhr({ url: r.Url, responseType: "document" });
						return r;
					});
					results.forEach(function (r) {
						r.documentPromise.then(function(x) {
							r.Description = "description";
							var keywordsElement = x.response.querySelector("head > meta[name=keywords]");
							r.Keywords = (keywordsElement ? keywordsElement.content : "");
							r.imageUrl = "";
							if(keywordsElement) resultsList.push(r);
						}, function (error) { /* gulp */ });
					});
				},
				function (err) {
					debugger;
				}
			);

			Ocho.AppBar.set({
				buttons: [{
					label: "Re:Search",
					icon: "rotate",
					section: "selection",
					click: function () {
					}
				}]
			});

			resultsListView = document.getElementById("resultsListView").winControl;
			resultsListView.itemDataSource = resultsList.dataSource;
			resultsListView.itemTemplate = document.getElementById("itemTemplate");
			resultsListView.oniteminvoked = function (e) {
				e.detail.itemPromise.then(function(item) {
					location.href = item.data.Url;
				});
			};
			resultsListView.onselectionchanged = function (e) {
				if (resultsListView.selection.count() >= 1) {
					document.getElementById("appbar").winControl.show();
				document.getElementById("appbar").winControl.sticky = true;
				} else {
					document.getElementById("appbar").winControl.hide();
			document.getElementById("appbar").winControl.sticky = false;
				}
			};
		}
	});
})();
